<?php
require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "function.php";

if (@$_SESSION['level']) {
    if ($_SESSION['level'] < 4) {
        header("location:apply_m.php");
    }

}

$type = !empty($_GET['type']) ? htmlspecialchars($_GET['type']) : 0; //报修类型
$apply_device_id = !empty($_GET['apply_device_id']) ? htmlspecialchars($_GET['apply_device_id']) : 0; //报修设备id

$isadmin=0;
//获取用户的联系方式
if (isset($uid)) {
    //有session 从数据库中读取用户名信息
    //$openid_str=$_SESSION['openid'];
    $row = $dosql->GetOne("SELECT * FROM `#@__user`  WHERE id='$uid'");
    if (is_array($row) && isset($row['id'])) {
        // 返回用户 id
        $userInfo = $row;
        $isadmin=$userInfo['isadmin'];
    }
}

?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>设备报修-<?php echo $cfg_webname; ?></title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="description" content="<?php echo $cfg_webname; ?>">
        <link rel="stylesheet" href="lib/weui.min.css">
        <link rel="stylesheet" href="css/jquery-weui.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">
        <link rel="stylesheet" href="css/demos.css?v=20201206.0059">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap.min.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap-theme.min.css">
        <script src="lib/jquery-2.1.4.js"></script>
        <script src="lib/fastclick.js"></script>
        <script>
            $(function () {
                FastClick.attach(document.body);
            });
        </script>
        <script src="js/jquery-weui.js"></script>
        <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.4&key=ad26780bfaabf0ca27ae6078e2e81682"></script>
        <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
    </head>

<body  ontouchstart>
<!--地图展示-->
<div id='container'></div>
<div id="tip" class="alert alert-error manage-alert manage-alert-error hidden"></div>

<!-- 地址信息 -->
<form name="form" id="form" method="post" action="">
    <div class="main" role="alert">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 报修信息</div>

        <div class="weui-cell weui-cells_form">
            <div class="weui-cell__hd">
                <label class="weui-label text-warning"> 单位：<span class="red">*</span> </label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" name="school" id="school" type="text" value="<?php echo $userInfo['school'] ?>">
            </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label text-warning"> 联系人： <span class="red">*</span></label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" name="truename" id="truename" type="text" value="<?php echo $userInfo['truename'] ?>">
            </div>
        </div>
        <div class="weui-cell ">
            <div class="weui-cell__hd">
                <label class="weui-label text-warning">手机号： <span class="red">*</span></label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" name="mobile" id="mobile" type="text" value="<?php echo $userInfo['mobile'] ?>">
            </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label text-warning">地址：</label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" type="text" name="address" id="address" value="<?php echo $userInfo['address'] ?>">

            </div>
        </div>


        <input type="hidden" id="latitude" name="latitude">
        <input type="hidden" id="longitude" name="longitude">
        <input type="hidden" id="accuracy" name="accuracy">
        <input type="hidden" name="apply_address_name" id="apply_address_name" value="">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label for="" class="weui-label f14"><i class="fa fa-building-o" aria-hidden="true"></i>
                        服务类型：<span class="red">*</span></label>
                </div>
                <div class="weui-cell__bd">
                    <select class="form-control" name="apply_type" id="apply_type">
                        <option value="0">请选择</option>
                        <?php
                        $dosql->Execute("SELECT * FROM  `#@__tasktype`  WHERE is_delete=0 and checkinfo=1 and id<5  order by orderid asc ");
                        while ($row2 = $dosql->GetArray()) {

                            if ($apply_device_id == $row2['id']) {
                                $selected = 'selected="selected"';
                            } else {
                                $selected = '';
                            }
                            echo '<option data-index="' . $row2['id'] . '"  value="' . $row2['id'] . '"  ' . $selected . ' >' . $row2['classname'] . '</option>';
                        }
                        ?>
                    </select>
                </div>
            </div>
            <div class="weui-cell hide" id="apply_device_box">
                <div class="weui-cell__hd">
                    <label for="" class="weui-label f14"><i class="fa fa-bars" aria-hidden="true"></i>
                        服务项目：<span class="red">*</span></label>
                </div>
                <div class="weui-cell__bd">
                    <select class="form-control" name="apply_device" id="apply_device">
                        <option value="0">请选择</option>
                    </select>
                </div>
            </div>
            <div class="weui-cells__title"> 故障描述<span class="red">*</span></div>
            <div class="weui-cells ">
                <div class="weui-cell">
                    <div class="weui-cell__bd">
                        <textarea class="form-control" name="content" id="content" placeholder="请输入型号，故障描述等" rows="3" onkeyup="words_deal();"></textarea>
                        <div class="weui-textarea-counter"><span id="textCount">0</span>/200</div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 开始-->
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title"> 图片上传</p>
                        <div class="weui-uploader__info">0/9</div>
                    </div>

                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">

                        </ul>
                        <div class="weui-uploader__input-box">
                            <input id="uploaderInput" class="weui-uploader__input">
                            <input type="hidden" name="picurls" id="picurls">
                            <input type="hidden" name="picfiles" id="picfiles">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 结束-->
        <input type="hidden" name="action" id="action" value="add"/>
        <input type="hidden" name="uid" id="uid" value="<?php echo $uid ?>"/>

</form>
</div>
<div class="sub_btn"><a href="javascript:;" class="btn btn-success btn-lg btn-block" onclick="cfm_order()" ;
                        return false;">立即报修</a></div>
<div class="clear"></div>

<script>

    /***************************************
     由于Chrome、IOS10等已不再支持非安全域的浏览器定位请求，为保证定位成功率和精度，请尽快升级您的站点到HTTPS。
     ***************************************/
    var map, geolocation;
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('container', {
        resizeEnable: true,
        zoom:16
    });
    var markers=[];
    map.on('click', showInfoClick);
    function showInfoClick(e){
        // 清除地图上所有添加的覆盖物
        if (markers) {
            for (var i = 0; i < markers.length; i += 1) {
                // 从点聚合中移除
                markers[i].setMap(null);
            }
            map.remove(markers);
            markers = [];
        }
        var longitude=e.lnglat.getLng();
        var latitude=e.lnglat.getLat();

        $("#latitude").val(latitude);
        $("#longitude").val(longitude);
        var zoom = map.getZoom(); //获取当前地图级别
        $("#accuracy").val(zoom);
        marker = new AMap.Marker({
            map: map,
            icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
            position: [longitude,latitude],
            offset: new AMap.Pixel(-13, -30)
        });
        markers.push(marker);

        $.ajax({
            url: "getMap.php?l=" + latitude + "&w=" + longitude,
            type: "GET",
            timeout: 2000,
            dataType: "json",
            success: function (data) {
                console.log('ok');
                var gps_address = data.result.formatted_addresses.recommend;
                //alert(gps_address);
                $("#address").val(gps_address);
                var text9 = '您选择的位置是 '+gps_address;
                $("#tip").html(text9);
                $("#tip").removeClass('hidden');
                var apply_address_name = data.result.address;
                //alert(gps_address);
                $("#apply_address_name").val(apply_address_name);


            },
            error: function (data) {
                console.log('error');

            }
        });


    }

    $(function () {
        //联动菜单
        $("#apply_type").change(function () {
            var tasktype = $('#apply_type option:selected').val();
            console.log(tasktype);
            if (tasktype > 0) {
                $("#apply_device_box").removeClass('hide');
                //联动
                $.ajax({
                    type: 'post',
                    url: "getTypeSub.php?typeid=" + tasktype,
                    //data: {areaId:areaId},
                    dataType: 'json',
                    success: function (res) {
                        console.log(res.data);
                        $("#apply_device").html("");
                        $("#apply_device").html(res.data);
                    }

                });

            } else {
                $("#apply_device_box").addClass('hide');
            }
        });
    });


    //描述字数限制
    function words_deal() {
        var curLength = $("#content").val().length;
        if (curLength > 200) {
            var num = $("#content").val().substr(0, 200);
            $("#content").val(num);
            alert("超过字数限制，多出的字将被截断！");
        }
        else {
            $("#textCount").text(200 - $("#content").val().length);
        }
    }


    function cfm_order() {
        if ($("#school").val() == "") {

            $.toast("单位不能为空", "forbidden");

            $("#school").focus();

            return false;

        }

        if ($("#truename").val() == "") {

            $.toast("联系人不能为空", "forbidden");

            $("#truename").focus();

            return false;

        }

        if ($("#mobile").val() == "") {

            $.toast("手机号码不能为空", "forbidden");

            $("#mobile").focus();

            return false;

        }


        if ($("#content").val() == "") {
            $.toast("请输入故障描述", "forbidden");
            $("#content").focus();
            return false;
        }
        var apply_device = $('#apply_device option:selected').val();
        if (apply_device == 0) {
            $.toast("请输选择服务类型", "forbidden");
            $("#content").focus();
            return false;
        }


        $("#form").submit();
    }


</script>

<?php


if (isset($action) and $action == 'add') {
    if (empty($content)) {
        echo '<script type="text/javascript">
	$.toast("操作不正确", function() {
		 window.location.href="index.php";
		});
	</script>';
        exit();
    }
    //如果是新客户，保存收货地址

    $school = htmlspecialchars($school);
    $truename = htmlspecialchars($truename);
    $mobile = htmlspecialchars($mobile);
    $address = htmlspecialchars($address);
    $json_address = $address . "-" . $school;
    $post_time = time();
    $picfiles=htmlspecialchars($picfiles);

    //写入crm
    $sql_crm = "INSERT INTO `#@__crm` (school, truename, mobile, address, addtime, checkinfo,uid) VALUES ( '$school','$truename', '$mobile', '$address', '$post_time', 'false','$uid')";
    $dosql->ExecNoneQuery($sql_crm);

    // 工单信息入库
    $apply_type = htmlspecialchars($apply_type);
    $apply_device = htmlspecialchars($apply_device);
    $content = htmlspecialchars($content);
    $picurls = "";
    $jindu = "3";
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());
    $picfiles_str="";
    if($picfiles!=""){
        $picfiles_arr=explode(",",$picfiles);
        $picfiles_str=json_encode($picfiles_arr);

    }

    $endtime=time()+14400;


    $fee = "";
    //调取任务奖励
    if ($apply_device > 0) {
        $fee_arr = $dosql->GetOne("SELECT * FROM `#@__task` WHERE id='$apply_device'");
        if (is_array($fee_arr) && isset($fee_arr['id'])) {
            $fee = $fee_arr['value'];
        }
    }


    //新建工单
    $sql222 = "insert into `#@__order`(openid,uid,school,truename,mobile,address,apply_type,apply_device,content,picurls,post_time,jindu,latitude,longitude,accuracy,picfiles,apply_address,apply_address_name,mode,is_accept,accept_time,begintime,endtime,fee) values ('$openid','$uid','$school','$truename','$mobile','$address','$apply_type','$apply_device','$content','$picurls','$post_time','$jindu','$latitude','$longitude','$accuracy','$picfiles_str','$apply_address_name','$address','q','1','$post_time','$post_time','$endtime','$fee')";
    $dosql->ExecNoneQuery($sql222);



    $orderid = $dosql->GetLastID();
    //插入更新的状态
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu) values ('$orderid','用户报修','$post_time','1')");
    $orderidname = date('Ymd', time()) . "-" . $orderid;
    //封装为json格式的数据
    $json = '{
	  "touser": "' . $openid . '" ,  
	  "template_id": "' . $cfg_apply . '",    
	  "url":"' . $cfg_weburl . 'wx/orderDetail.php?orderid=' . $orderid . '",      
	  "data": {
		  "first": {
			  "value": "您好，报修成功，即将派单维修", 
			  "color": "#f71b03"
		  }, 
		  "keyword1": {
			  "value": "' . $orderidname . '", 
			  "color": "#173177"
		  }, 
		  "keyword2": {
			  "value": "' . $post_time2 . '", 
			  "color": "#173177"
		  },
		  "keyword3": {
			  "value": "' . getDeviceName($apply_device) . '", 
			  "color": "#0e48cb"
		  },
		  "keyword4": {
			  "value": " ' . $json_address . '", 
			  "color": "#173177"
		  },
		  "keyword5": {
			  "value": "' . $content . '", 
			  "color": "#173177"
		  },
		  "remark": {
			  "value": "系统正在派单，请稍等。马上会有工程师和您联系，请保持通讯畅通。", 
			  "color": "#f71b03"
		  } 
	  }
	}';
    sendWxMsg($json);

    //给有抢单权限的群发抢单消息
    //获取抢单的工程师
    $mode_user = array();
    $dosql->Execute("SELECT `openid` FROM  `#@__user`  WHERE `level`='3' and qiang='1'  ORDER BY id asc");
    while ($row_qaing = $dosql->GetArray()) {
        $mode_user[] = $row_qaing['openid'];
    }


    //获取抢单的工程师
/*    $mode_user = [];
    $dosql->Execute("SELECT `openid` FROM  `#@__user`  WHERE `level`='3'   ORDER BY id asc");
    while ($row_qaing = $dosql->GetArray()) {
        $mode_user[] = $row_qaing['openid'];
    }*/



    //处理工单
    foreach ($mode_user as $key => $val) {
        //获取工程师 openid
        $openid_str = $val;
        $orderidname = date('Ymd', time()) . "-" . $orderid;
        //封装为json格式的数据
        $repairname = getRepairMode($apply_device);
        //$repairname = $repairname . "  奖励  " . $fee;
        $send_body['touser'] = $openid_str;
        $send_body['template_id'] = $cfg_neworder;
        $send_body['url'] = $cfg_weburl . 'wx/morderDetail.php?orderid=' . $orderid;
        $send_body['data']['first']['value'] = "📢 您好,用户报修系统自动下发抢单任务。请处理";
        $send_body['data']['first']['color'] = "#FF0000";
        $send_body['data']['keyword1']['value'] = $orderidname;
        $send_body['data']['keyword1']['color'] = "#173177";
        $send_body['data']['keyword2']['value'] = $repairname;
        $send_body['data']['keyword2']['color'] = "#FF0000";
        $send_body['data']['keyword3']['value'] = $post_time2;
        //$send_body['data']['keyword3']['color'] = "#FF0000";
        $send_body['data']['keyword4']['value'] = "💗".$school."-".$truename;
        $send_body['data']['keyword4']['color'] = "#0e48cb";
        $send_body['data']['keyword5']['value'] = "⛳".$address;
        $send_body['data']['keyword5']['color'] = "#0e48cb";
        $send_body['data']['remark']['value'] = "👉请点击抢单，手慢无。服务热线:". $cfg_hotline."👈";
        $send_body['data']['remark']['color'] = "#FF0000";

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $g_AccessToken;
        $res=$jssdk->https_curl_json($url, $send_body, 'json');
        //$jssdk->return_json_body(['code'=>0,'msg'=>'添加成功']);


    }

    //系统发送抢单任务
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu) values ('$orderid','系统发下抢单任务','$post_time','1')");

    echo '<script type="text/javascript">
	$.toast("报修成功", function() {
		 window.location.href="order.php";
		});
	</script>';
    exit();

}

?>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    wx.config({
        debug: false,
        appId: '<?php echo $signPackage["appId"];?>',
        timestamp: <?php echo $signPackage["timestamp"];?>,
        nonceStr: '<?php echo $signPackage["nonceStr"];?>',
        signature: '<?php echo $signPackage["signature"];?>',
        jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'openAddress',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getLocation'
        ]
    });
    wx.ready(function () {
        // 分享
        var urlurl = window.location.href;
        var shareData = {
            title: '驻马市店天诚电子科技有限公司-在线报修',
            desc: '在线报修，2小时内响应。48-72小时内完修。维修状态实时查看。',
            link: urlurl,
            imgUrl: 'https://tc.98198.cn/uploads/image/20201201/1606820605_712020.png'
        };


        wx.onMenuShareAppMessage(shareData);
        wx.onMenuShareTimeline(shareData);
        wx.onMenuShareQQ(shareData);
        wx.onMenuShareQZone(shareData);
        //地址
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                $("#latitude").val(latitude);
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                $("#longitude").val(longitude);
                var speed = res.speed; // 速度，以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                $("#accuracy").val(accuracy);
                map.setCenter([longitude, latitude]); //设置地图中心点
                marker = new AMap.Marker({
                    map: map,
                    icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                    position: [longitude,latitude],
                    offset: new AMap.Pixel(-13, -30)
                });

                $.ajax({
                    url: "getMap.php?l=" + latitude + "&w=" + longitude,
                    type: "GET",
                    timeout: 2000,
                    dataType: "json",
                    success: function (data) {
                        console.log('ok');
                        var gps_address = data.result.formatted_addresses.recommend;
                        //alert(gps_address);
                        $("#address").val(gps_address);
                        var apply_address_name = data.result.address;
                        //alert(gps_address);
                        $("#apply_address_name").val(apply_address_name);
                    },
                    error: function (data) {
                        console.log('error');

                    }
                });
            },
            cancel: function (res) {
                $.alert("你拒绝授权获取地理位置，我们的工程师无法快速定位。时效性可能会延时，请谅解", " 温馨提示");
            }

        });
        //打开相册
        var images = {
            localId: [],
            serverId: []
        };
        var filepaths = [];
        document.querySelector('#uploaderInput').onclick = function () {
            wx.chooseImage({
                count: 9, // 默认9
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var picurls = res.localIds;
                    var uploadCount = 0;
                    var pic_length = res.localIds.length;
                    var m = 0;
                    var upload = function () {
                        wx.uploadImage({
                            localId: picurls[uploadCount],
                            success: function (res) {
                                //如果还有照片，继续上传
                                var serverId = res.serverId; // 返回图片的服务器端ID
                                console.log(serverId);
                                $.ajax({
                                    type: 'POST',
                                    url: "getFile.php",
                                    data: {serverId: serverId},
                                    dataType: 'JSON',
                                    success: function (result) {
                                        if (result.errno == 0) {
                                            console.log(result.msg);
                                            if (result.msg === "ok") {
                                                filepaths.push(result.filename);
                                                $("#picfiles").val(filepaths);
                                                $("#uploaderFiles").append('<li class="weui-uploader__file" style="background-image:url(' + result.filename + ')"></li>');
                                            } else {
                                                $.alert("上传失败<br/> 请联系管理员！", "温馨提示");
                                            }
                                        }
                                    }
                                });
                                uploadCount++;
                                if (uploadCount < pic_length) {
                                    upload();
                                }
                            }
                        });
                    }
                    upload();
                }
            });
        }
        //


    });
</script>
<?php require_once('footer.php'); ?>
